package pr.platerecognization;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.OcrRequestParams;
import com.baidu.ocr.sdk.model.OcrResponseResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class network extends AppCompatActivity {
    Button img, pto;
    TextView result, time;
    ImageView imageView;
    private boolean hasLicense;
    private String mFilePath;
    private static String[][] fullNames;

    static {
        fullNames = new String[][]{
                {"安徽省", "皖"},
                {"北京市", "京"},
                {"福建省", "闽"},
                {"甘肃省", "甘"},
                {"广东省", "粤"},
                {"广西壮族自治区", "桂"},
                {"贵州省", "贵"},
                {"海南省", "琼"},
                {"河北省", "冀"},
                {"河南省", "豫"},
                {"黑龙江省", "黑"},
                {"湖北省", "鄂"},
                {"湖南省", "湘"},
                {"吉林省", "吉"},
                {"江苏省", "苏"},
                {"江西省", "赣"},
                {"辽宁省", "辽"},
                {"内蒙古自治区", "蒙"},
                {"宁夏回族自治区", "宁"},
                {"青海省", "青"},
                {"山东省", "鲁"},
                {"山西省", "晋"},
                {"陕西省", "陕"},
                {"上海市", "沪"},
                {"四川省", "川"},
                {"天津市", "津"},
                {"西藏自治区", "藏"},
                {"新疆维吾尔自治区", "新"},
                {"云南省", "云"},
                {"浙江省", "浙"},
                {"重庆市", "渝"}
        };
    }

    private static final Map<String, String[][]> cities = new HashMap<>(fullNames.length);
    long currentTime1;

    static {

        cities.put("皖", new String[][]{
                {"A", "合肥市"},
                {"B", "芜湖市"},
                {"C", "蚌埠市"},
                {"D", "淮南市"},
                {"E", "马鞍山市"},
                {"F", "淮北市"},
                {"G", "铜陵市"},
                {"H", "安庆市"},
                {"J", "黄山市"},
                {"K", "阜阳市"},
                {"L", "宿州市"},
                {"M", "滁州市"},
                {"N", "六安市"},
                {"P", "宣城市"},
                {"Q", "巢湖市"},
                {"R", "池州市"},
                {"S", "毫州市"}

        });

        cities.put("京", new String[][]{
                {"A", ""},
                {"B", ""},
                {"C", ""},
                {"E", ""}
        });


        cities.put("闽", new String[][]{
                {"A", "福州市"},
                {"B", "莆田市"},
                {"C", "泉州市"},
                {"D", "厦门市"},
                {"E", "漳州市"},
                {"F", "龙岩市"},
                {"G", "三明市"},
                {"H", "南平市"},
                {"J", "宁德市"},
                {"K", "省直系统"}

        });

        cities.put("甘", new String[][]{
                {"A", "兰州市"},
                {"B", "嘉峪关市"},
                {"C", "金昌市"},
                {"D", "白银市"},
                {"E", "天水市"},
                {"F", "酒泉市"},
                {"G", "张掖市"},
                {"H", "威武市"},
                {"J", "定西市"},
                {"K", "陇南市"},
                {"L", "平凉市"},
                {"M", "庆阳市"},
                {"N", "临夏回族自治州"},
                {"P", "甘南藏族自治州"}

        });


        cities.put("粤", new String[][]{
                {"A", "广州市"},
                {"B", "深圳市"},
                {"C", "珠海市"},
                {"D", "汕头市"},
                {"E", "佛山市"},
                {"F", "韶关市"},
                {"G", "湛江市"},
                {"H", "肇庆市"},
                {"J", "江门市"},
                {"K", "茂名市"},
                {"L", "惠州市"},
                {"M", "梅州市"},
                {"N", "汕尾市"},
                {"P", "河源市"},
                {"Q", "阳江市"},
                {"R", "清远市"},
                {"S", "东莞市"},
                {"T", "中山市"},
                {"U", "潮州市"},
                {"V", "揭阳市"},
                {"W", "云浮市"},
                {"X", "顺德区"},
                {"Y", "南海区"},
                {"Z", "港澳进入内地车辆"}

        });


        cities.put("桂", new String[][]{
                {"A", "南宁市"},
                {"B", "柳州市"},
                {"C", "桂林市"},
                {"D", "梧州市"},
                {"E", "北海市"},
                {"F", "南宁地区"},
                {"G", "柳州地区"},
                {"H", "桂林地区"},
                {"J", "贺州市"},
                {"K", "玉林市"},
                {"L", "百色市"},
                {"M", "河池市"},
                {"N", "钦州市"},
                {"P", "防城港市"},
                {"R", "贵港市"}

        });


        cities.put("贵", new String[][]{
                {"A", "贵阳市"},
                {"B", "六盘水市"},
                {"C", "遵义市"},
                {"D", "铜仁市"},
                {"E", "黔西南布依族自治州"},
                {"F", "毕节市"},
                {"G", "安顺市"},
                {"H", "黔东南苗族侗族自治州"},
                {"J", "黔南布依族自治州"}

        });


        cities.put("琼", new String[][]{
                {"A", "海口市"},
                {"B", "三亚市"},
                {"C", "琼海市"},
                {"D", "五指山市"},
                {"E", "洋浦开发区"}

        });


        cities.put("冀", new String[][]{
                {"A", "石家庄市"},
                {"B", "唐山市"},
                {"C", "秦皇岛市"},
                {"D", "邯郸市"},
                {"E", "邢台市"},
                {"F", "保定市"},
                {"G", "张家口市"},
                {"H", "承德市"},
                {"J", "沧州市"},
                {"R", "廊坊市"},
                {"S", "沧州市"},
                {"T", "衡水市"}

        });


        cities.put("豫", new String[][]{
                {"A", "郑州市"},
                {"B", "开封市"},
                {"C", "洛阳市"},
                {"D", "平顶山市"},
                {"E", "安阳市"},
                {"F", "鹤壁市"},
                {"G", "新乡市"},
                {"H", "焦作市"},
                {"J", "濮阳市"},
                {"K", "许昌市"},
                {"L", "漯河市"},
                {"M", "三门峡市"},
                {"N", "商丘市"},
                {"P", "周口市"},
                {"Q", "驻马店市"},
                {"R", "南阳市"},
                {"S", "信阳市"},
                {"U", "济源市"}

        });


        cities.put("黑", new String[][]{
                {"A", "哈尔滨市"},
                {"B", "齐齐哈尔市"},
                {"C", "牡丹江市"},
                {"D", "佳木斯市"},
                {"E", "大庆市"},
                {"F", "伊春市"},
                {"G", "鸡西市"},
                {"H", "鹤岗市"},
                {"J", "双鸭山市"},
                {"K", "七台河市"},
                {"L", "松花江地区——已并入哈尔滨市"},
                {"M", "绥化市"},
                {"N", "黑河市"},
                {"P", "大兴安岭地区"},
                {"R", "农恳地区"}

        });
        cities.put("鄂", new String[][]{
                {"A", "武汉市"},
                {"B", "黄石市"},
                {"C", "十堰市"},
                {"D", "荆州市"},
                {"E", "宜昌市"},
                {"F", "襄樊市"},
                {"G", "鄂州市"},
                {"H", "荆门市"},
                {"J", "黄冈市"},
                {"K", "孝感市"},
                {"L", "咸宁市"},
                {"M", "仙桃市"},
                {"N", "潜江市"},
                {"P", "神农架林区"},
                {"Q", "恩施土家族苗族自治州"},
                {"R", "天门市"},
                {"S", "随州市"}

        });
        cities.put("湘", new String[][]{
                {"A", "长沙市"},
                {"B", "株洲市"},
                {"C", "湘潭市"},
                {"D", "衡阳市"},
                {"E", "邵阳市"},
                {"F", "岳阳市"},
                {"G", "张家界市"},
                {"H", "益阳市"},
                {"J", "常德市"},
                {"K", "娄底市"},
                {"L", "郴州市"},
                {"M", "永州市"},
                {"N", "怀化市"},
                {"U", "湘西土家族苗族自治州"}

        });
        cities.put("吉", new String[][]{
                {"A", "长春市"},
                {"B", "吉林市"},
                {"C", "四平市"},
                {"D", "辽源市"},
                {"E", "通化市"},
                {"F", "白山市"},
                {"G", "白城市"},
                {"H", "延边朝鲜族自治州"},
                {"J", "松原市"}

        });
        cities.put("苏", new String[][]{
                {"A", "南京市"},
                {"B", "无锡市"},
                {"C", "徐州市"},
                {"D", "常州市"},
                {"E", "苏州市"},
                {"F", "南通市"},
                {"G", "连云港市"},
                {"H", "淮安市"},
                {"J", "盐城市"},
                {"K", "扬州市"},
                {"L", "镇江市"},
                {"M", "泰州市"},
                {"U", "苏州市增补"}

        });
        cities.put("赣", new String[][]{
                {"A", "南昌市"},
                {"B", "赣州市"},
                {"C", "宜春市"},
                {"D", "吉安市"},
                {"E", "上饶市"},
                {"F", "抚州市"},
                {"G", "九江市"},
                {"H", "景德镇市"},
                {"J", "萍乡市"},
                {"K", "新余市"},
                {"L", "鹰潭市"},
                {"M", "南昌市，省直系统"}

        });
        cities.put("辽", new String[][]{
                {"A", "沈阳市"},
                {"B", "大连市"},
                {"C", "鞍山市"},
                {"D", "抚顺市"},
                {"E", "本溪市"},
                {"F", "丹东市"},
                {"G", "锦州市"},
                {"H", "营口市"},
                {"J", "阜新市"},
                {"K", "辽阳市"},
                {"L", "盘锦市"},
                {"M", "铁岭市"},
                {"N", "朝阳市"},
                {"P", "葫芦岛市"}

        });
        cities.put("蒙", new String[][]{
                {"A", "呼和浩特市"},
                {"B", "包头市"},
                {"C", "乌海市"},
                {"D", "赤峰市"},
                {"E", "呼伦贝尔市"},
                {"F", "兴安盟"},
                {"G", "通辽市"},
                {"H", "锡林郭勒盟"},
                {"J", "乌兰察布盟"},
                {"K", "鄂尔多斯市"},
                {"L", "巴彦淖尔盟"},
                {"M", "阿拉善盟"}

        });
        cities.put("宁", new String[][]{
                {"A", "银川市"},
                {"B", "石嘴山市"},
                {"C", "银南市"},
                {"D", "固原市"},
                {"E", "中卫市"}

        });
        cities.put("青", new String[][]{
                {"A", "西宁市"},
                {"B", "海东市"},
                {"C", "海北藏族自治州"},
                {"D", "黄南藏族自治州"},
                {"E", "海南藏族自治州"},
                {"F", "果洛藏族自治州"},
                {"G", "玉树藏族自治州"},
                {"H", "海西蒙古族藏族自治州"}

        });
        cities.put("鲁", new String[][]{
                {"A", "济南市"},
                {"B", "青岛市"},
                {"C", "淄博市"},
                {"D", "枣庄市"},
                {"E", "东营市"},
                {"F", "烟台市"},
                {"G", "潍坊市"},
                {"H", "济宁市"},
                {"J", "泰安市"},
                {"K", "威海市"},
                {"L", "日照市"},
                {"M", "滨州市"},
                {"N", "德州市"},
                {"P", "聊城市"},
                {"Q", "临沂市"},
                {"R", "菏泽市"},
                {"S", "莱芜市"},
                {"U", "青岛市增补"},
                {"V", "潍坊市增补"}

        });
        cities.put("晋", new String[][]{
                {"A", "太原市"},
                {"B", "大同市"},
                {"C", "阳泉市"},
                {"D", "长治市"},
                {"E", "晋城市"},
                {"F", "朔州市"},
                {"G", "雁北地区"},
                {"H", "忻州市"},
                {"J", "吕梁地区"},
                {"K", "晋中市"},
                {"L", "临汾市"},
                {"M", "运城市"}

        });
        cities.put("陕", new String[][]{
                {"A", "西安市"},
                {"B", "铜川市"},
                {"C", "宝鸡市"},
                {"D", "咸阳市"},
                {"E", "渭南市"},
                {"F", "汉中市"},
                {"G", "安康市"},
                {"H", "商洛市"},
                {"J", "延安市"},
                {"K", "榆林市"},
                {"V", "杨凌高新农业示范区"}

        });
        cities.put("沪", new String[][]{
                {"A", ""},
                {"B", ""},
                {"C", ""},
                {"D", ""},
                {"R", "崇明、长兴"}

        });
        cities.put("川", new String[][]{
                {"A", "成都市"},
                {"B", "绵阳市"},
                {"C", "自贡市"},
                {"D", "攀枝花市"},
                {"E", "沪州市"},
                {"F", "德阳市"},
                {"G", "成都市增补"},
                {"H", "广元市"},
                {"J", "遂宁市"},
                {"K", "内江市"},
                {"L", "乐山市"},
                {"M", "资阳市"},
                {"Q", "宜宾市"},
                {"R", "南充市"},
                {"S", "达州市"},
                {"T", "雅安市"},
                {"U", "阿坝藏族羌族自治州"},
                {"V", "甘孜藏族自治州"},
                {"W", "凉山彝族自治州"},
                {"X", "广安市"},
                {"Y", "巴中市"},
                {"Z", "眉山市"}

        });
        cities.put("津", new String[][]{
                {"A", ""},
                {"B", ""},
                {"C", ""}

        });
        cities.put("藏", new String[][]{
                {"A", "拉萨市"},
                {"B", "昌都地区"},
                {"C", "山南地区"},
                {"D", "日喀则地区"},
                {"E", "那曲地区"},
                {"F", "阿里地区"},
                {"G", "林芝地区"},
                {"H", "驻四川省天全县车辆管理所"},
                {"J", "驻青海省格尔木市车辆管理所"}

        });
        cities.put("新", new String[][]{
                {"A", "乌鲁木齐市"},
                {"B", "昌吉回族自治州"},
                {"C", "石河子市"},
                {"D", "奎屯市"},
                {"E", "博尔塔拉蒙古自治州"},
                {"F", "伊犁哈萨克自治州直辖县"},
                {"G", "塔城市"},
                {"H", "阿勒泰市"},
                {"J", "克拉玛依市"},
                {"K", "吐鲁番市"},
                {"L", "哈密市"},
                {"M", "巴音郭楞蒙古自治州"},
                {"N", "阿克苏市"},
                {"P", "克孜勒苏柯尔克孜自治州"},
                {"Q", "喀什市"},
                {"R", "和田市"}

        });
        cities.put("云", new String[][]{
                {"A", "昆明市"},
                {"A-V", "东川市"},
                {"C", "昭通市"},
                {"D", "曲靖市"},
                {"E", "楚雄彝族自治州"},
                {"F", "玉溪市"},
                {"G", "红河哈尼族彝族自治州"},
                {"H", "文山壮族苗族自治州"},
                {"J", "思茅市"},
                {"K", "西双版纳傣族自治州"},
                {"L", "大理白族自治州"},
                {"M", "保山市"},
                {"N", "德宏傣族景颇族自治州"},
                {"P", "丽江市"},
                {"Q", "怒江傈僳族自治州"},
                {"R", "迪庆藏族自治州"},
                {"S", "临沧地区"}

        });
        cities.put("浙", new String[][]{
                {"A", "杭州市"},
                {"B", "宁波市"},
                {"C", "温州市"},
                {"D", "绍兴市"},
                {"E", "湖州市"},
                {"F", "嘉兴市"},
                {"G", "金华市"},
                {"H", "衢州市"},
                {"J", "台州市"},
                {"K", "丽水市"},
                {"L", "舟山市"}

        });
        cities.put("渝", new String[][]{
                {"A", "市区（江南）"},
                {"B", "市区（江北）"},
                {"C", "永川区"},
                {"F", "万州区"},
                {"G", "涪陵区"},
                {"H", "黔江区"}
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR|
                View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR|
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        OCR.getInstance(this).initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                hasLicense = true;
            }

            @Override
            public void onError(OCRError ocrError) {
            }
        }, "aip.license", getApplicationContext());

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_network);

        img = findViewById(R.id.net_ToPick_Button);
        pto = findViewById(R.id.net_ToPhoto_Button);
        result = findViewById(R.id.net_ShowResult);
        time = findViewById(R.id.net_ShowTime);
        imageView = findViewById(R.id.net_ImageView);
        pto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mFilePath = getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath();

                try {
                    if(!new File(mFilePath).exists()) {
                        new File(mFilePath).mkdirs();
                        new File(mFilePath,"temp.jpg").createNewFile();
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }
                // 指定拍照意图
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 加载路径图片路径
                Uri mUri ;

                if(Build.VERSION.SDK_INT>Build.VERSION_CODES.N)
                    mUri=FileProvider.getUriForFile(getApplicationContext(),BuildConfig.APPLICATION_ID+".PhotoProvider",new File(mFilePath,"temp.jpg"));
                else
                    mUri=Uri.fromFile(new File(mFilePath,"temp.jpg"));

                // 指定存储路径，这样就可以保存原图了
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
                startActivityForResult(openCameraIntent, 200);
            }
        });
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(Intent.ACTION_PICK).setType("image/*"),100);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK && null != data) {

            Uri selectedImage = data.getData();
            String picturePath;
            Cursor cursor = getContentResolver().query(selectedImage, null, null, null, null);
            if (cursor == null)
                picturePath = selectedImage.getPath();
            else {
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
                picturePath = cursor.getString(columnIndex);
            }
            imageView.setImageURI(selectedImage);
            if (hasLicense) {
                /**
                 * 用Android SDK麻烦的地方就是图片里的车牌必须是正着摆放的，
                 * 不是正着摆放的话，就需要进行矫正
                 * 没有，用原生安卓也可以矫正
                 * 用代码检测图片方向，然后旋转图片，就可以了
                 * 试试
                 * 识别是需要时间的
                 * 你应该拿的不是车牌图
                 */


                OcrRequestParams params = new OcrRequestParams();
                params.setImageFile(new File(picturePath));
                currentTime1 = System.currentTimeMillis();
                OCR.getInstance(this).recognizeLicensePlate(params, new OnResultListener<OcrResponseResult>() {
                    @Override
                    public void onResult(final OcrResponseResult ocrResponseResult) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                JSONObject jsonObj = null;
                                try {
                                    jsonObj = new JSONObject(ocrResponseResult.getJsonRes().toString());
                                    JSONObject jO = jsonObj.getJSONObject("words_result");
                                    String code=jO.getString("number");
                                    String city=StaCi(code.substring(0,1),code.substring(1,2));
                                    long diff = System.currentTimeMillis() - currentTime1;
                                    result.setText("车牌:" + code + "\n" + "颜色:" + jO.getString("color") + "\n" +  "签发地区:" + city + "\n");
                                    time.setText("时间:" + String.valueOf(diff) + "ms");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                //text.setText(ocrResponseResult.getJsonRes());
                            }
                        });
                    }

                    @Override
                    public void onError(final OCRError ocrError) {

                        /**
                         * 没识别出来，会执行该接口方法
                         */

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                result.setText("无法识别");
                                //ocrError.toString()
                            }
                        });
                    }
                });
            } else {
                result.setText("未授予权限");
            }
        } else if (requestCode == 200) {

            /**
             * 测试下
             */
            try {

                /**
                 * 只要拍照就会有返回，
                 * 没按快门的话，就用默认图片代替
                 */
                //new File(mFilePath,"temp.jpg")    文件对象
                //父路径加子路径等于   完整真实路径mFilePath+File.separator+"temp.jpg"
                //可以使用File类的不同构造方法达到同样的目的

//                FileInputStream is = new FileInputStream(new File(mFilePath+File.separator+"temp.jpg"));

                FileInputStream is = new FileInputStream(new File(mFilePath, "temp.jpg"));

                //不同的构造方法而已
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                imageView.setImageBitmap(bitmap);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            OcrRequestParams params = new OcrRequestParams();
            params.setImageFile(new File(mFilePath + File.separator + "temp.jpg"));
            currentTime1 = System.currentTimeMillis();
            OCR.getInstance(this).recognizeLicensePlate(params, new OnResultListener<OcrResponseResult>() {
                @Override
                public void onResult(final OcrResponseResult ocrResponseResult) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            JSONObject jsonObj = null;
                            try {

                                // long currentTime1 = System.currentTimeMillis();
                                jsonObj = new JSONObject(ocrResponseResult.getJsonRes().toString());
                                JSONObject jO = jsonObj.getJSONObject("words_result");
                                //JSONArray Belive = jO.getJSONArray("probability");
                                String code = jO.getString("number");
                                String city = StaCi(code.substring(0, 1), code.substring(1, 2));
                                long diff = System.currentTimeMillis() - currentTime1;
                                result.setText("车牌:" + code + "\n" + "颜色:" + jO.getString("color") + "\n" +  "签发地区:" + city + "\n");
                                time.setText("时间:" + String.valueOf(diff) + "ms");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            //text.setText(ocrResponseResult.getJsonRes());
                        }
                    });
                }

                @Override
                public void onError(final OCRError ocrError) {
                    /**
                     * 没识别出来，会执行该接口方法
                     */
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            result.setText("无法识别");

                            //ocrError.toString()
                        }
                    });
                }
            });
            // 把流解析成bitmap,此时就得到了清晰的原图
        }
    }

    private static String StaCi(String C, String l) {
        String result = "";
        for (int x = 0; x < fullNames.length; x++) {
            if (C.equals(fullNames[x][1])) {
                result += fullNames[x][0];
            }
        }
        String[][] temp = cities.get(C);
        for (int s = 0; s < temp.length; s++) {
            if (l.equals(temp[s][0])) {
                result += temp[s][1];
            }
        }
        return result;
    }
}
